using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Pikapika.Models;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using System.Linq.Expressions;

namespace Pikapika.Areas.Admin.Controllers
{
    public class NovelController : CrudControllerBase<Novel>
    {

        protected override ObjectSet<Novel> GetObjectSet(PikapikaDBEntities ctx)
        {
            return ctx.Novels;
        }

        public ActionResult Create(int publisherId)
        {
            return View(new Novel { PublisherId = publisherId });
        }

        [NonAction]
        public override ActionResult Create()
        {
            return base.Create();
        }

        protected override IQueryable<Novel> GetObjectQuery(PikapikaDBEntities ctx)
        {
            IQueryable<Novel> query = ctx.Novels.Include("Publisher");
            RouteData.ProcessOptionalId("publisherId", (publisherId) =>
            {
                query = query.Where(n => n.PublisherId == publisherId);
                ViewBag.PublisherId = publisherId;
            });
            return query;
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext.Result is ViewResult) {
                ViewBag.AllPublishers = new Lazy<IEnumerable<Publisher>>(() =>
                {
                    using (var ctx = new PikapikaDBEntities())
                    {
                        return ctx.Publishers.ToList();
                    }
                });
            }
            base.OnActionExecuted(filterContext);
        }
    }
}
